<!DOCTYPE html>
<html>
  <head><meta name="generator" content="Hexo 3.8.0">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="火骑小龙龙づ博客 vue mint-ui js html css 前端">
  <meta name="keyword" content="hexo-theme, vuejs">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      Mongoose学习 | 火骑小龙龙づ博客
    
  </title>
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/css/plugins/gitment.css">
  <script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js"></script>
  <script src="/js/qrious.js"></script>
<script src="/js/gitment.js"></script>
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


</head>
<div class="wechat-share">
  <img src="/css/images/logo.png">
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>火骑小龙龙づ博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags" class="item-link">Tags</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/categories" class="item-link">Categories</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives" class="item-link">Archives</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/project" class="item-link">Project</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about" class="item-link">About</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags" class="menu-link">Tags</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/categories" class="menu-link">Categories</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives" class="menu-link">Archives</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/project" class="menu-link">Project</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about" class="menu-link">About</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>


    <div id="article-banner">
  <h2>Mongoose学习</h2>
  <p class="post-date">2019-09-11</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><p>Mongoose 入门</p>
<a id="more"></a>
<blockquote>
<p>安装</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install mongoose --save</span><br></pre></td></tr></table></figure>
<blockquote>
<p>引入mongoose 并 连接数据库</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mongoose =  <span class="built_in">require</span>(<span class="string">"mongoose"</span>);</span><br><span class="line">mongoose.connect(<span class="string">'mongodb://localhost:27017/test'</span>)</span><br><span class="line"><span class="comment">/* 配置了密码账号的链接方式 */</span></span><br><span class="line">mongoose.connect(<span class="string">'mongodb://eggadmin:123456@localhost:27017/eggcms'</span>)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>定义Schema(数据集合也就是表)</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> UserSchema = <span class="keyword">new</span> mongoose.Schema(&#123;</span><br><span class="line">    name: <span class="built_in">String</span>,</span><br><span class="line">    age: <span class="built_in">Number</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>创建数据模型</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">    格式： mongoose.model 里面可以传入两个参数也可以传入三个参数 </span></span><br><span class="line"><span class="comment">    mongoose.model（参数 1:模型名称（首字母大写） ， 参数 2:Schema）</span></span><br><span class="line"><span class="comment">    mongoose.model（ 参数 1:模型名称（ 首字母大写） ， 参数 2:Schema， 参数 3:数据库集名称）</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    如果传入 2 个参数的话:这个模型会和模型名称相同的复数的数据库建立连接： 如通过下面方法创建模型， 那么这个模型将会操作 users 这个集合。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    如果传入 3 个参数的话:模型默认操作第三个参数定义的集合名称</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">const</span> User = mongoose.model(<span class="string">'User'</span>, UserSchema); <span class="comment">// 数据库表的名称</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>查找数据</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">User.find(&#123;<span class="attr">name</span>:<span class="string">'lisi'</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">err, docs</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(err) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(err);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(docs)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">/* API: find  findOne  findById where */</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>添加数据</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> u = <span class="keyword">new</span> User(&#123; <span class="attr">name</span>: <span class="string">'wangwu'</span>, <span class="attr">age</span>: <span class="number">12</span> &#125;)</span><br><span class="line">u.save( <span class="function"><span class="keyword">function</span>(<span class="params">err</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(err) <span class="keyword">return</span> handleError(err)</span><br><span class="line">    <span class="comment">// saved</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// or</span></span><br><span class="line"></span><br><span class="line">User.create(&#123; <span class="attr">name</span>: <span class="string">'wangwu'</span>, <span class="attr">age</span>: <span class="number">12</span> &#125;,<span class="function"><span class="keyword">function</span>(<span class="params">err, small</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (err) <span class="keyword">return</span> handleError(err);</span><br><span class="line">    <span class="comment">// saved!</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>修改数据</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">User.updateOne(&#123; <span class="attr">name</span>: <span class="string">'lisi'</span> &#125;, &#123;<span class="attr">name</span>:<span class="string">'zhaoliu'</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">err, res</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(err) <span class="keyword">return</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'success'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>删除数据</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">User.deleteOne(&#123;<span class="attr">_id</span>:<span class="string">'5b72ada84e284f0acc8d318a'</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">err</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(err) <span class="keyword">return</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'delete success'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">User.remove(&#123;<span class="attr">age</span>: <span class="number">20</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">err</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(err) <span class="keyword">return</span>;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">/* API: </span></span><br><span class="line"><span class="comment">    deleteOne: 删除与conditions集合匹配的第一个文档。表现得像remove()，但无论single选项如何，最多只删除一个文档。 </span></span><br><span class="line"><span class="comment">    remove: conditions从集合中删除所有匹配的文档。要仅删除匹配的第一个文档，请conditions将该single选项设置为true。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>mongoose 默认参数</p>
</blockquote>
<ul>
<li><p>检测数据库是否连接成功</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">mongoose.connect(<span class="string">'mongodb://localhost:27017/test'</span>,&#123; <span class="attr">useNewUrlParser</span>: <span class="literal">true</span> &#125;,<span class="function"><span class="keyword">function</span>(<span class="params">err</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(err) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'connect fild'</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'connect success'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">/* &#123; useNewUrlParser: true &#125;: 当前版本的url（数据库的链接）解析器过期了，未来版本会被移除，如果要使用新的配置这个属性就可以了 */</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>创建model， 操作指定的表</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> UserModel = mongoose.model(<span class="string">'User'</span>, UserSchema, <span class="string">'user'</span>);</span><br><span class="line"><span class="comment">/* 第三个参数，未设置，默认操作User表，设置了，操作指定的user表 */</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>增加的数据字段如果在定义<code>Schema</code>中没有定义，Mongodb不会把多出来的该字段插入数据库</p>
</li>
<li><p>字段的默认值</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> UserSchema = <span class="keyword">new</span> mongoose.Schema(&#123;</span><br><span class="line">    name: <span class="string">'lisi'</span>,</span><br><span class="line">    status: &#123;</span><br><span class="line">        type: <span class="built_in">Number</span>,</span><br><span class="line">        <span class="keyword">default</span>: <span class="number">1</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 新增数据时会默认有status字段 */</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<blockquote>
<p>mongoose 模块化</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ touch db.js <span class="comment">// 配置数据库连接</span></span><br><span class="line">$ touch user.js <span class="comment">// 创建 user的model 来操作数据库</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>mongoose 预定义修饰符和自定义修饰符</p>
</blockquote>
<ul>
<li><p>预定义修饰符</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> UserSchema = <span class="keyword">new</span> mongoose.Schema(&#123;</span><br><span class="line">    name: &#123;</span><br><span class="line">        type: <span class="built_in">String</span>,</span><br><span class="line">        trim: <span class="literal">true</span></span><br><span class="line">    &#125;,</span><br><span class="line">    age: <span class="built_in">Number</span>,</span><br><span class="line">    status: &#123;</span><br><span class="line">        type: <span class="built_in">Number</span>,</span><br><span class="line">        <span class="keyword">default</span>: <span class="number">1</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 预定义修饰符：对增加的数据进行格式化 lowercase, uppercase, trim */</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>自定义修饰符</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 场景 用户添加的img url 有时候会没有http:// 没有的时候自动添加 */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> ImgSchema = <span class="keyword">new</span> mongoose.Schema(&#123;</span><br><span class="line">    imgName: <span class="built_in">String</span>,</span><br><span class="line">    imgSrc: &#123;</span><br><span class="line">        type: <span class="built_in">String</span>,</span><br><span class="line">        set: <span class="function"><span class="keyword">function</span>(<span class="params">url</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">if</span>(!url) <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">            <span class="keyword">if</span>(url.indexOf(<span class="string">'http://'</span>)!=<span class="number">0</span> &amp;&amp; url.indexOf(<span class="string">'https://'</span>)!=<span class="number">0</span>)&#123;</span><br><span class="line">                url = <span class="string">'http://'</span> + url;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> url;</span><br><span class="line">        &#125;,</span><br><span class="line">        get: <span class="function"><span class="keyword">function</span>(<span class="params">url</span>)</span>&#123;</span><br><span class="line">            <span class="keyword">if</span>(!url) <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">            <span class="keyword">if</span>(url.indexOf(<span class="string">'http://'</span>)!=<span class="number">0</span> &amp;&amp; url.indexOf(<span class="string">'https://'</span>)!=<span class="number">0</span>)&#123;</span><br><span class="line">                url = <span class="string">'http://'</span> + url;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> url;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> img = mongoose.model(<span class="string">'Img'</span>, ImgSchema);</span><br><span class="line"><span class="built_in">console</span>.log(img.imgSrc); <span class="comment">/* 此时的get方法才会起作用 */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 自定义修饰符： Getter（不建议使用，获取的是model实例中的数据，并非是数据库中的数据）  Setter  */</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<blockquote>
<p>mongoose 设置索引</p>
</blockquote>
<ul>
<li><p>mongodb原生设置索引</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* mongodb 设置索引 */</span></span><br><span class="line">db.user.ensureIndex(&#123;<span class="string">'id'</span>:<span class="number">1</span>&#125;)</span><br><span class="line">db.user.getIndexes()</span><br><span class="line">db.user.dropIndex(&#123;<span class="string">'id'</span>:<span class="number">1</span>&#125;)</span><br><span class="line"><span class="comment">/* 1: 表示升序 -1：表示降序 */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 设置唯一索引 */</span></span><br><span class="line">db.user.ensureIndex(&#123;<span class="string">'userId'</span>:<span class="number">1</span>&#125;,&#123;<span class="string">'unique'</span>: <span class="literal">true</span>&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p>mongoose设置索引</p>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> UserSchema = <span class="keyword">new</span> mongoose.Schema(&#123; <span class="attr">name</span>: <span class="built_in">String</span>, <span class="attr">index</span>: <span class="literal">true</span> &#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>扩展mongoose的方法</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> DeviceSchema = <span class="keyword">new</span> mongoose.Schema(&#123;</span><br><span class="line">    name: <span class="built_in">String</span>,</span><br><span class="line">    sn: <span class="built_in">String</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> deviceModel = mongoose.model(<span class="string">"device"</span>, DeviceSchema);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 扩展静态方法: 通过sn查询设备 */</span></span><br><span class="line">DeviceSchema.statics.findBySn = <span class="function"><span class="keyword">function</span>(<span class="params">sn, callback</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.find(&#123;<span class="string">'sn'</span>: sn&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">err, res</span>) </span>&#123;</span><br><span class="line">        callback(err, res)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">deviceModel.findBySn(<span class="string">'123456789'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, res</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(err) <span class="keyword">return</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(res)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 扩展实例方法 */</span></span><br><span class="line">DeviceSchema.methods.print = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="keyword">this</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> devicePro = <span class="keyword">new</span> deviceModel(&#123;</span><br><span class="line">    name:<span class="string">'抽风机'</span>,</span><br><span class="line">    sn: <span class="string">'12345678'</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">devicePro.print(); <span class="comment">// &#123;name:'抽风机', sn: '12345678'&#125;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>mongoose 数据校验</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* api: required（必传字段） </span></span><br><span class="line"><span class="comment">        max|min: 用于Number类型，最大/小数值</span></span><br><span class="line"><span class="comment">        enum：枚举类型，要求数据必须满足枚举值， 用于String类型</span></span><br><span class="line"><span class="comment">        match: 增加的数据必须符合match（正则）的规则 用于String类型</span></span><br><span class="line"><span class="comment">        maxlength|minlength: 最大/小长度 用于String类型</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    枚举：enum：['1','2']  字段接收的值必须在enum中包含</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 自定义 数据校验 */</span></span><br><span class="line"><span class="keyword">const</span> UserSchema = mongoose.Schema(&#123;</span><br><span class="line">    name: <span class="built_in">String</span>,</span><br><span class="line">    valitade: <span class="function"><span class="keyword">function</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> value.length &gt;= <span class="number">10</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>mongoose 中使用aggregate聚合管道</p>
</blockquote>
<ul>
<li>MongoDB Aggregation 管道操作符与表达式</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align:center">管道操作符</th>
<th style="text-align:center">功能描述      </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">$project</td>
<td style="text-align:center">增加，删除，重命名字段</td>
</tr>
<tr>
<td style="text-align:center">$match</td>
<td style="text-align:center">条件匹配。 只满足条件的文档才能进入下一阶段</td>
</tr>
<tr>
<td style="text-align:center">$limit</td>
<td style="text-align:center">限制结果的数量</td>
</tr>
<tr>
<td style="text-align:center">$skip</td>
<td style="text-align:center">跳过文档的数量</td>
</tr>
<tr>
<td style="text-align:center">$sort</td>
<td style="text-align:center">条件排序</td>
</tr>
<tr>
<td style="text-align:center">$group</td>
<td style="text-align:center">条件组合结果 统计</td>
</tr>
<tr>
<td style="text-align:center">$lookup</td>
<td style="text-align:center">$lookup 操作符 用以引入其它集合的数据 （表关联查询）</td>
</tr>
</tbody>
</table>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">userModel.aggregate(</span><br><span class="line">    [</span><br><span class="line">        &#123;</span><br><span class="line">            $lookup: &#123;</span><br><span class="line">                <span class="keyword">from</span>: <span class="string">"user_item"</span>,  <span class="comment">/* user表和user_item表关联 */</span></span><br><span class="line">                localField: <span class="string">"user_id"</span>,</span><br><span class="line">                foreignField: <span class="string">"user_id"</span>,</span><br><span class="line">                <span class="keyword">as</span>: <span class="string">"user_list"</span>,  <span class="comment">/* 查询到的数据 */</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">/* 多表关联 */</span></span><br><span class="line">        &#123;</span><br><span class="line">            $lookup: &#123;</span><br><span class="line">                <span class="keyword">from</span>: <span class="string">"user_depart"</span>,  <span class="comment">/* user表和user_item表关联 */</span></span><br><span class="line">                localField: <span class="string">"user_depart_id"</span>,</span><br><span class="line">                foreignField: <span class="string">"user_depart_id"</span>,</span><br><span class="line">                <span class="keyword">as</span>: <span class="string">"user_list"</span>,  <span class="comment">/* 查询到的数据 */</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">            $sort:&#123;<span class="string">"user_name"</span>:<span class="number">-1</span>&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    ], </span><br><span class="line">    <span class="function"><span class="keyword">function</span>(<span class="params">err, res</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(err) <span class="keyword">return</span>;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">JSON</span>.stringify(res))</span><br><span class="line">    &#125;</span><br><span class="line">)</span><br><span class="line"><span class="comment">/* user表 关联 user_item表 关联 user_depart表 */</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>mongoose populate 关联查询</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">const</span> UserSchema = mongoose.Schema(&#123;</span><br><span class="line">    name:<span class="built_in">String</span>,</span><br><span class="line">    id: &#123;</span><br><span class="line">        type: <span class="built_in">String</span>,</span><br><span class="line">        ref: <span class="string">'user_item'</span>,  <span class="comment">/* user id 和 user_item 建立连接 */</span></span><br><span class="line">    &#125;,</span><br><span class="line">    user_depart: &#123;</span><br><span class="line">        type: <span class="built_in">String</span>,</span><br><span class="line">        ref: <span class="string">'user_depart'</span> <span class="comment">/* user id 和 user_depart 建立连接 */</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 引入 userModel, useritemModel, userdepartModel */</span></span><br><span class="line">userModel.find(&#123;&#125;).populate(<span class="string">'id'</span>).exec(<span class="function"><span class="keyword">function</span>(<span class="params">err, res</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(err) <span class="keyword">return</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(res);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>MongoDB 的导入导出 <a href="https://www.cnblogs.com/liuxiaowei/p/9257523.html" target="_blank" rel="noopener">大牛笔记</a></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">导入：  mongoexport -d dbname -c collectionname -o file --type json/csv -f field</span></span><br><span class="line"><span class="comment">        参数说明：</span></span><br><span class="line"><span class="comment">            -d ：数据库名</span></span><br><span class="line"><span class="comment">            -c ：collection名</span></span><br><span class="line"><span class="comment">            -o ：输出的文件名</span></span><br><span class="line"><span class="comment">            --type ： 输出的格式，默认为json</span></span><br><span class="line"><span class="comment">            -f ：输出的字段，如果-type为csv，则需要加上-f "字段名"</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">导出：  mongoimport -d dbname -c collectionname --file filename --headerline --type json/csv -f field</span></span><br><span class="line"><span class="comment">        参数说明：</span></span><br><span class="line"><span class="comment">            -d ：数据库名</span></span><br><span class="line"><span class="comment">            -c ：collection名</span></span><br><span class="line"><span class="comment">            --type ：导入的格式默认json</span></span><br><span class="line"><span class="comment">            -f ：导入的字段名</span></span><br><span class="line"><span class="comment">            --headerline ：如果导入的格式是csv，则可以使用第一行的标题作为导入的字段</span></span><br><span class="line"><span class="comment">            --file ：要导入的文件</span></span><br><span class="line"><span class="comment"> */</span></span><br></pre></td></tr></table></figure></section>
    <!-- Tags START -->
    
      <div class="tags">
        <span>Tags:</span>
        
  <a href="/tags#Mongoose">
    <span class="tag-code">Mongoose</span>
  </a>

      </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/2019/09/11/suibi/重新开始/">
        <span class="nav-arrow">← </span>
        
          重新开始
        
      </a>
    
    
      <a class="nav-right" href="/2019/09/12/biancheng/React/React踩坑集合/">
        
          React业务踩坑集合
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://taoaiyi1108.github.io/2019/09/11/biancheng/Mongo/Mongoose学习/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

     // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()
        
        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })

    // qrcode
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });

    // gitment
    var gitmentConfig = "taoaiyi1108";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "Mongoose学习",
        owner: "taoaiyi1108",
        repo: "taoaiyi1108.github.io",
        oauth: {
          client_id: "0f87e490e00ee3fd87ef",
          client_secret: "4a9d2b148e7971c2201ad12131ce8bf8159ccd2e"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  })();
</script>

<script>
  var disqus_shortname = '';
  
  var disqus_url = 'http://taoaiyi1108.github.io/2019/09/11/biancheng/Mongo/Mongoose学习/';
  
  (function(){
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = '//go.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
  })();
</script>

    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2019 火骑小龙龙 | Proudly powered by <a href="https://hexo.io" target="_blank">Hexo</a>
    <br>
    感谢大神 <a href="https://github.com/yanm1ng" target="_blank">yanm1ng</a> 对本博客的技术支持
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->

<script src="/js/script.js"></script>
  </body>
</html>